package com.qf.reaml;

import com.qf.pojo.SysUsers;
import com.qf.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

public class MyUserRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//        SysUsers user =(SysUsers) principalCollection.getPrimaryPrincipal();
//        int userId = user.getId();
//        Set<String> roles = userService.findRolesByUid(userId);
//        Set<String> perm = userService.findPermByUid(userId);
//        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
//        simpleAuthorizationInfo.setRoles(roles);
//        simpleAuthorizationInfo.setStringPermissions(perm);
//        return simpleAuthorizationInfo;
        //1. 获取认证的时候shiro框架中session存储的用户对象
        SysUsers user = (SysUsers)principalCollection.getPrimaryPrincipal();
        int userId = user.getId();

        //2. 根据用户id, 到数据库角色表中获取用户的角色信息
        Set<String> roleList = userService.findRolesByUid(userId);

        //3. 根据用户id, 到数据库权限表或者菜单表中获取用户的权限信息
        Set<String> permList = userService.findPermByUid(userId);

        //4. 封装shiro规定的角色权限对象
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();

        //5. 将角色数据赋予shiro的权限对象
        authorizationInfo.setRoles(roleList);

        //6. 将权限数据赋予shiro的权限对象
        authorizationInfo.setStringPermissions(permList);

        //7. 返回shiro的权限对象给, securityManager核心对象
        return authorizationInfo;


    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String username =(String) authenticationToken.getPrincipal();
        String password = new String((char[]) authenticationToken.getCredentials());
        SysUsers user = userService.findUserByName(username);

        if (user==null){
            throw new UnknownAccountException("用户不存在!");
        }
        if (!password.equals(user.getPassword())){
            throw new IncorrectCredentialsException("密码不对");
        }

        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, this.getName());
        return info;
    }
}
